using UnityEngine;
using QFramework;
using MoonSharp.VsCodeDebugger.SDK;
using ProjectSurvivor;
using QAssetBundle;
using System.Collections;
using System.Linq;
using System.Collections.Generic;

namespace QFrameworkSurvivor
{
	public partial class GetAllExp : PowerUp
    {
        static IEnumerator FlyToPlayerStart()
        {
            IEnumerable<PowerUp> exps = FindObjectsByType<Exp>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
            IEnumerable<PowerUp> coins = FindObjectsByType<Coin>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);

            int count = 0;
            foreach (var item in exps.Concat(coins).OrderByDescending(e => e.InScreen).ThenBy(e=>e.Distance2D(Player.Default)))
            {
                if (!item.InScreen)
                {
                    if(count>2)
                    {
                        count = 0;
                        yield return new WaitForEndOfFrame();
                    }
                }
                else
                {
                    if (count > 5)
                    {
                        count = 0;
                        yield return new WaitForEndOfFrame();
                    }
                }
                count++;
                ActionKit.OnUpdate.Register(() =>
                {
                    var player = Player.Default;
                    if (player && item)
                    {
                        item.transform.Translate(player.NormalizedDirection2DFrom(item) * Time.deltaTime * 5f);
                    }
                }).UnRegisterWhenGameObjectDestroyed(item);
            };
        }
        protected override Collider2D Collider2D => SelfCollider2D;
        private void OnTriggerEnter2D(Collider2D other)
        {
            if(other.GetComponent<CollectableArea>())
            {
                FlyingToPlayer=true;
            }
        }
        protected override void Execute()
        {
            AudioKit.PlaySound(Sfx.GETALLEXP);

            PowerUpManager.Default.StartCoroutine(FlyToPlayerStart());

            this.DestroyGameObjGracefully();
        }
    }
}
